<template>
  <div v-loading="loading">
    <vue-json-editor
      v-model="jsonObject"
      :showBtns="false"
      mode="tree"
      lang="zh"
      @json-change="onJsonChange"
      @has-error="onError" />
    <div class="btn">
      <el-button type="primary" @click="onSubumit">保存</el-button>
    </div>
  </div>
</template>

<script>
import vueJsonEditor from "vue-json-editor"
import { getFile, writeFile } from "@/api/admin/file"
import { defaultBuckName, defaultFileName } from "@/util/constants"

export default {
  components: {
    vueJsonEditor,
  },
  data() {
    return {
      jsonObject: null,
      loading: true,
      hasError: false,
    }
  },
  created() {
    getFile(defaultBuckName, defaultFileName).then((res) => {
      this.jsonObject = res.data
      this.loading = false
    })
  },
  methods: {
    onJsonChange() {
      this.hasError = false
    },
    onError() {
      this.hasError = true
    },
    onSubumit() {
      if (this.hasError) {
        this.$message.error(`json格式错误`)
        return false
      }
      let str = new Blob([JSON.stringify(this.jsonObject)], { type: "application/json" })
      let formData = new FormData()
      formData.append("file", str)
      writeFile(formData, this.fileName).then((res) => {
        if (res.data.code == 0) {
          this.$message.success("保存成功")
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
  },
}
</script>
<style>
.jsoneditor-poweredBy {
  display: none;
}
div.jsoneditor-outer {
  height: 500px;
}
</style>
<style scoped>
.btn {
  text-align: center;
  margin-top: 10px;
}
</style>
